package com.example.demo02.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo02.common.Result;
import com.example.demo02.dto.ProductWithSupplierInfo;
import com.example.demo02.entity.InventoryRecord;
import com.example.demo02.entity.Product;
import com.example.demo02.entity.Supplier;
import com.example.demo02.service.InventoryRecordService;
import com.example.demo02.service.ProductService;
import com.example.demo02.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/inventory")
@CrossOrigin
public class InventoryRecordController {

    @Autowired
    private InventoryRecordService inventoryRecordService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SupplierService supplierService;


    @PostMapping("/add")
    public Result add(@RequestBody InventoryRecord inventoryRecord) {
        try {
            Integer recordId =   inventoryRecordService.addInventoryRecord(inventoryRecord);

            return Result.success(recordId); // 直接返回订单 ID
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
    }

    @PutMapping("/update")
    public Result update(@RequestBody InventoryRecord inventoryRecord) {
        inventoryRecordService.updateById(inventoryRecord);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        inventoryRecordService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        inventoryRecordService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<InventoryRecord> inventoryRecordList = inventoryRecordService.list();
        return Result.success(inventoryRecordList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        InventoryRecord inventoryRecord = inventoryRecordService.getById(id);
        return Result.success(inventoryRecord);
    }




    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) String productName,
                               @RequestParam(required = false) String supplierName) {
        QueryWrapper<InventoryRecord> queryWrapper = new QueryWrapper<>();
        if (productName != null) {
            Integer productId = productService.getOne(new QueryWrapper<com.example.demo02.entity.Product>().eq("product_name", productName)).getProductId();
            if (productId != null) {
                queryWrapper.eq("product_id", productId);
            }
        }
        if (supplierName != null) {
            Integer supplierId = supplierService.getOne(new QueryWrapper<com.example.demo02.entity.Supplier>().eq("supplier_name", supplierName)).getSupplierId();
            if (supplierId != null) {
                queryWrapper.eq("supplier_id", supplierId);
            }
        }
        Page<InventoryRecord> page = new Page<>(pageNum, pageSize);
        Page<InventoryRecord> inventoryRecordPage = inventoryRecordService.page(page, queryWrapper);

        List<ProductWithSupplierInfo> productWithSupplierInfoList = inventoryRecordPage.getRecords().stream().map(record -> {
            Product product = productService.getById(record.getProductId());
            Supplier supplier = supplierService.getById(record.getSupplierId());
            return new ProductWithSupplierInfo(record, product, supplier);
        }).collect(Collectors.toList());

        return Result.success(productWithSupplierInfoList);
    }
}